package com.zhuhao.basic.map;

import lombok.Data;
import org.junit.Test;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * java-合并两个Map
 * 有点像map.put()操作，从map中获取给定的key，如有值就对新value、老value进行处理，如没有则直接放入
 *
 * @author halk
 * @date 2022/9/29 16:08
 **/
public class MergeStringDemo {

    private static Map<String, String> map1 = new HashMap<>();
    private static Map<String, String> map2 = new HashMap<>();

    static {
        map1.put("1", "1");
        map1.put("2", "2");
        map2.put("1", "A");
        map2.put("2", "B");
    }

    /**
     * merge  computeIfPresent都可以用于合并，但是newV,oldV的顺序相反，computeIfPresent是newV在前
     */
    @Test
    public void testMerge() {
        map1.forEach((k, v) -> System.out.println(k + " : " + v));
        map2.forEach((k, v) -> System.out.println(k + " : " + v));

        //可以对两个map进行合并操作，相同的key，可以对两个map的value进行合并去重处理
        map1.forEach((k, v) ->
                map2.merge(
                        k,
                        v,
                        (oldValue, newValue) -> {
                            System.out.println(k);
                            System.out.println(v);
                            System.out.println("v1" + oldValue);
                            System.out.println("v2" +newValue);
                            return oldValue.equals(newValue) ? oldValue : oldValue + newValue;
                        }
                )
        );

        System.out.println("map2");
        map2.forEach((k, v) -> System.out.println(k + " : " + v));
    }

    @Test
    public void testMerge2() {
        map1.forEach((k, v) -> System.out.println(k + " : " + v));
        map2.forEach((k, v) -> System.out.println(k + " : " + v));

        //可以对两个map进行合并操作，相同的key，可以对两个map的value进行合并去重处理
        map1.forEach((k, v) ->
                map2.computeIfPresent(
                        k,
                        (newValue, oldValue) -> {
                            System.out.println(k);
                            System.out.println(v);
                            System.out.println("v1" + newValue);
                            System.out.println("v2" +oldValue);
                            return oldValue.equals(newValue) ? oldValue : oldValue + newValue;
                        }
                )
        );

        System.out.println("map2");
        map2.forEach((k, v) -> System.out.println(k + " : " + v));
    }

}

